#ifndef __UDPSERVER_HPP__
#define __UDPSERVER_HPP__

#include <iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

using namespace LogModule;

const static int gsockfd = -1;
// const static std::string gdefaultip = "127.0.0.1"; // 本地环回IP
const static uint16_t gdefaultport = 8080; // 端口号

class UdpServer
{
public:
    UdpServer(uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port), _isrunning(false)
    {}

    ~UdpServer()
    {
        if(_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

    void InitServer()
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0); // 网络通信、UDP协议
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is: " << _sockfd;

        // // 2. 填充socket信息(IP + 端口号)
        // struct sockaddr_in local;
        // bzero(&local, sizeof(local));    // 设置为全0
        // local.sin_family = AF_INET;      // 网络通信
        // local.sin_port = ::htons(_port); // 端口: 主机序列->网络序列
        // // local.sin_addr.s_addr = ::inet_addr(_ip.c_str()); // IP: 字符串->字节序列->网络序列
        // local.sin_addr.s_addr = INADDR_ANY; // 接收服务器中的任意IP地址

        // 3. bind网络信息到内核中
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in client; // 存储客户端: IP + 端口号
            socklen_t len = sizeof(client);

            // 1. 接收客户端发来的消息
            ssize_t n = ::recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&client), &len);
            if (n > 0)
            {
                // 2. 服务器打印客户端发送的消息
                buffer[n] = 0;
                InetAddr cli(client);
                // uint16_t clientport = ::ntohs(client.sin_port);      // 将网络序列->主机序列
                // std::string clientip = ::inet_ntoa(client.sin_addr); // 将网络序列->字节序列->字符串
                std::string clientinfo = cli.Ip() + ":" + std::to_string(cli.Port()) + " # " + buffer;
                LOG(LogLevel::DEBUG) << clientinfo;

                // 3. 发送消息给客户端
                std::string message = "echo# ";
                message += buffer;
                ::sendto(_sockfd, message.c_str(), message.size(), 0, CONV(&client), sizeof(client));
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd;
    // uint16_t _port; // 服务器端口号
    // std::string _ip; // 服务器IP
    InetAddr _addr;
    bool _isrunning; // 服务器运行状态
};

#endif